package com.meiyu.live.ui.mine;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseFragment;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.net.param.GetPageParams;
import com.meiyu.live.net.response.GetFunsResponse;
import com.meiyu.live.popj.PersonalInfo;
import com.meiyu.live.util.RippleUtils;
import com.meiyu.live.widget.MSGView;
import com.meiyu.live.widget.UserInfoDialog;

/**
 * 粉丝贡献排行榜Fragment
 */
public class FansContributionFragment extends BaseFragment {

    public static final String CONTRIBUTION_TYPE = "contribution_type";

    private LayoutInflater inflater;
    private MSGView msgView;
    private SwipeRefreshLayout refreshLayout;
    private ListView listView;
    private DataListAdapter adapter;
    private View footerView;
    private UserInfoDialog userInfoDialog;

    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private static final int PAGE_SIZE = 10;
    private int index = 1;
    private boolean hasMore = true;
    private GetFunsResponse getFocusResponse = new GetFunsResponse();

    /**
     * 粉丝贡献类型，0 送礼榜，1 分享榜，2 时长榜
     */
    private int contribution_type = 0;

    public FansContributionFragment() {
    }

    public static FansContributionFragment newInstance(int type) {
        FansContributionFragment fragment = new FansContributionFragment();
        Bundle args = new Bundle();
        args.putInt(CONTRIBUTION_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            contribution_type = getArguments().getInt(CONTRIBUTION_TYPE, 0);
        }
    }

    @Override
    public int getContextView() {
        return R.layout.fragment_fanscontribution;
    }

    @Override
    protected void init() {
        inflater = LayoutInflater.from(getActivity());
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        msgView = (MSGView) findViewById(R.id.msgView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(true);
            }
        });
        listView = (ListView) findViewById(R.id.listview);

        footerView = inflater.inflate(R.layout.view_loadmore, null);
        listView.addFooterView(footerView);
        footerView.setVisibility(View.GONE);

        adapter = new DataListAdapter();
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { // 判断滚动到底部
                    if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1) && hasMore) {
                        footerView.setVisibility(View.VISIBLE);
                        getData(false);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        getData(true);
    }

    private void getData(final boolean reload) {
        msgView.showLoading();
        //热门直播接口
        if (reload) {
            index = 1;
            hasMore = true;
        }
        int area[] = {PAGE_SIZE, index + PAGE_SIZE - 1};
        GetPageParams gp = new GetPageParams(area);
        switch (contribution_type) {
            case 0:
                gp.setUrl(Constant.UrlParams.GIFT);
                break;
            case 1:
                gp.setUrl(Constant.UrlParams.FANSSHARE);
                break;
            case 2:
                gp.setUrl(Constant.UrlParams.FANSDURATION);
                break;
        }
        request(gp, GetFunsResponse.class, new Response.Listener<GetFunsResponse>() {
            @Override
            public void onResponse(GetFunsResponse getFocusResponse) {
                refreshLayout.setRefreshing(false);
                footerView.setVisibility(View.GONE);
                if (getFocusResponse != null) {
                    if (reload) {
                        FansContributionFragment.this.getFocusResponse.getHash().clear();
                    }
                    FansContributionFragment.this.getFocusResponse.getHash().addAll(getFocusResponse.getHash());
                    index += PAGE_SIZE;
                    if (getFocusResponse.getHash().size() < PAGE_SIZE) {
                        hasMore = false;
                    }
                    adapter.notifyDataSetChanged();
                    if (getFocusResponse.getHash().size() == 0) {
                        msgView.show_empty();
                    } else {
                        msgView.dismiss();
                    }
                } else {
                    msgView.show_error();
                }
            }
        });
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        refreshLayout.setRefreshing(false);
        footerView.setVisibility(View.GONE);
        msgView.show_error();
        super.onErrorResponse(volleyError);
    }

    class DataListAdapter extends BaseAdapter {

        private class ViewHolder {
            View layout_root;
            ImageView iv_avatar;
            TextView tv_name, tv_level, tv_signature;
        }

        int mainColor = getActivity().getResources().getColor(R.color.main_theme_color);

        View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int index = (int) view.getTag();
                final PersonalInfo bean = getFocusResponse.getHash().get(index);
                String id = bean.getUser_id() + "";
                userInfoDialog = new UserInfoDialog(getActivity());
                userInfoDialog.setUserId(id);
                userInfoDialog.show();
            }
        };

        @Override
        public int getCount() {
            return getFocusResponse != null && getFocusResponse.getHash() != null ? getFocusResponse.getHash().size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_fans, null);
                holder = new ViewHolder();
                holder.layout_root = convertView.findViewById(R.id.layout_root);
                RippleUtils.setRippleDrawable(holder.layout_root, mainColor);
                holder.layout_root.setOnClickListener(onItemClickListener);
                holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_level = (TextView) convertView.findViewById(R.id.tv_level);
                holder.tv_signature = (TextView) convertView.findViewById(R.id.tv_signature);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.layout_root.setTag(position);
            final PersonalInfo bean = getFocusResponse.getHash().get(position);
            imageLoader.displayImage(bean.getAvatar(), holder.iv_avatar, options);
            holder.tv_name.setText(bean.getName());
            String level = bean.getLevel();
            holder.tv_level.setText(TextUtils.isEmpty(level) ? "1" : level + "级");
            holder.tv_signature.setText(bean.getSignature());
            return convertView;
        }
    }
}
